<template>
  <div class="appointment-container">
    <Header />

    <el-card class="main-card">
      <h2>{{ userType === 1 ? '患者预约管理' : '我的预约记录' }}</h2>

      <!-- 加载状态 -->
      <el-skeleton :loading="loading" animated :rows="5">
        <template #default>
          <!-- 预约卡片列表 -->
          <div class="appointment-list">
            <el-card
                v-for="appointment in appointments"
                :key="appointment.appointId"
                class="appointment-card"
            >
              <div class="card-content">
                <div class="info-row">
                  <el-icon><User /></el-icon>
                  <span class="label">患者：</span>
                  <span>{{ appointment.userRealName }}</span>
                </div>

                <div class="info-row">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span class="label">科室：</span>
                  <span>{{ appointment.name }}</span>
                </div>

                <div class="info-row">
                  <el-icon><Avatar /></el-icon>
                  <span class="label">医生：</span>
                  <span>{{ appointment.doctorRealName }}</span>
                </div>

                <div class="info-row">
                  <el-icon><Calendar /></el-icon>
                  <span class="label">预约时间：</span>
                  <span>{{ formatDate(appointment.appointTime) }}</span>
                </div>

                <div class="info-row">
                  <el-icon><Clock /></el-icon>
                  <span class="label">状态：</span>
                  <el-tag :type="statusTagType(appointment.status)">
                    {{ statusText(appointment.status) }}
                  </el-tag>
                </div>

                <!-- 医生操作按钮 -->
                <div v-if="userType === 1 && appointment.status === 0" class="action-buttons">
                  <el-button
                      type="success"
                      size="small"
                      @click="handleApprove(appointment.appointId)"
                  >接受</el-button>
                  <el-button
                      type="danger"
                      size="small"
                      @click="handleReject(appointment.appointId)"
                  >驳回</el-button>
                </div>
              </div>
            </el-card>

            <!-- 空状态 -->
            <el-empty
                v-if="!loading && appointments.length === 0"
                description="暂无预约记录"
            />
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
                v-model:current-page="pageData.page"
                v-model:page-size="pageData.size"
                :total="pageData.total"
                :page-size="pageData.size"
                layout="prev, pager, next"
                @current-change="changePageHandler"
                background
            />
          </div>
        </template>
      </el-skeleton>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {dayjs, ElMessage} from 'element-plus'
import {User, OfficeBuilding, Calendar, Clock, Avatar} from '@element-plus/icons-vue'
import Header from '@/components/Header.vue'
import {getUserInfo} from "@/utils/auth.js";
import {appointmentHandler, appointmentSelectByDoctor, appointmentSelectPageByUser} from "@/api/appointment.js";

// 用户类型 (从本地存储获取)
const userType = ref(getUserInfo()?.type || 2)
const user = ref(getUserInfo())

// 分页数据
const pageData = ref({
  page: 1,
  size: 4 // 默认每页4条
})

// 预约数据
const appointments = ref([])
const loading = ref(false)

// 分页后的数据

// 状态映射
const statusText = (status) => {
  return {
    0: '待处理',
    1: '已接受',
    2: '已驳回'
  }[status]
}

const statusTagType = (status) => {
  return {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }[status]
}

// 日期格式化
const formatDate = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

// 获取预约数据
const fetchAppointments = async () => {
  try {
    loading.value = true
    if (userType.value === 2) {
      // 病人获取自己的预约
      pageData.value.phone = user.value.phone
      const res = await appointmentSelectPageByUser(pageData.value)
      appointments.value = res.data.records
      pageData.value.total = res.data.total
    }
    if (userType.value === 1) {
      pageData.value.doctorId = user.value.doctorId
      pageData.value.size = 3
      //TODO: 根据医生获取所有患者预约
      const res = await appointmentSelectByDoctor(pageData.value)
      appointments.value = res.data.records
      pageData.value.total = res.data.total
    }


    if (userType.value === 1) {
      // 医生获取所有待处理预约
      appointments.value = appointments.value.filter(item => item.status === 0 || item.status === 1)
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理预约操作
const handleApprove = async (appointId) => {
  try {
    // 调用审批API
    await updateAppointmentStatus(appointId, 1)
    ElMessage.success('已接受预约')
    await fetchAppointments()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleReject = async (appointId) => {
  try {
    // 调用驳回API
    await updateAppointmentStatus(appointId, 2)
    ElMessage.success('已驳回预约')
    await fetchAppointments()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 模拟API调用
const updateAppointmentStatus = async (appointId, status) => {
  await appointmentHandler({appointId: appointId, status: status})
  await fetchAppointments()
}

const changePageHandler = async (page) => {
  pageData.value.page = page
  await fetchAppointments()
}

onMounted(fetchAppointments)
</script>

<style scoped>
.appointment-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.main-card {
  margin-top: 20px;
}

.appointment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.appointment-card {
  .card-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .info-row {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;

    .label {
      color: #666;
      min-width: 70px;
    }
  }

  .action-buttons {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
